package cn.cytong.util;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.lang.Strings;

import java.util.Iterator;
import java.util.Map;

/**
 * 自动根据系统环境变量RUNNING_MODE来加载配置，如果运行模式配置为dev，
 * 则通过本类获取配置的时候，会自动尝试在key的前面加上"dev."，尝试搜索开发环境下的配置值
 * Created by orangeJ on 2016-10-19.
 */
public class ProfilePropertiesProxy extends PropertiesProxy {
    private static final String Mode_Property_Name = "RUNNING_MODE";
    private String mode = null;

    public ProfilePropertiesProxy() {
        super();
        readMode();
    }

    private void readMode() {
        try {
            Map<String, String> map = System.getenv();
            String systemMode = map.get(Mode_Property_Name);
            if (!Strings.isEmpty(systemMode))
                mode = systemMode;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String get(String key) {
        if (Strings.isEmpty(mode))
            return super.get(key);

        return Strings.sNull(super.get(buildModeKey(key)), super.get(key));
    }

    @Override
    public String get(String key, String defaultValue) {
        String val = get(key);
        return Strings.sNull(val, defaultValue);
    }

    private String buildModeKey(String key) {
        if (Strings.isEmpty(mode)) return key;
        return "%" + mode + "." + key;
    }
}
